//
//
//
//
#ifndef _THREAD_MANAGER_H_
#define _THREAD_MANAGER_H_

#include "common.h"
#include "Mutex.h"
#include "Condition.h"
#include "Semaphore.h"
#include "BaseJob.h"
#include "WorkThread.h"
// Singleton
class ThreadManager
{
	public:
		static ThreadManager* Instance();
		static void DestroyInstance();
		
		static void* ThreadEntry(void* pArg);

		bool Initialize(U32 threadNum);

		// Job
		U32 AddJob(BaseJob* pJob);
		bool WaitAll();
		bool WaitAll(U32 seconds);

		void Report(std::ostream& os);

		//
		// Signal Exit signal to all work threads
		// threads will exit when no jobs in job pool
		void SignalExit(void);

	protected:
		ThreadManager();
		~ThreadManager();

		Mutex _threadPoolMutex;
		Mutex _jobListMutex;

		std::list<BaseJob*> _jobList;
		std::list<WorkThread*> _threadList;

		Semaphore _threadSem;

		static const U32 MAX_ALLOW_THREAD_NUM = 500;

		// useconds
		static const U32 IDLE_THREAD_SLEEP_TIME = 1000;

	private:
		static ThreadManager* _sInstance;
		static Mutex _instanceMutex;
};

#endif // _THREAD_MANAGER_H_
